package model

import (
	"context"
	"fmt"

	"github.com/Masterminds/squirrel"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ TaskModel = (*customTaskModel)(nil)

type (
	// TaskModel is an interface to be customized, add more methods here,
	// and implement the added methods in customTaskModel.
	TaskModel interface {
		taskModel
		RowBuilder() squirrel.SelectBuilder
		Truncate(ctx context.Context)
		FindAll(ctx context.Context) ([]*Task, error)
		FindAllTaskByGroupId(ctx context.Context, groupId int64) ([]*Task, error)
	}

	customTaskModel struct {
		*defaultTaskModel
	}
)

// NewTaskModel returns a model for the database table.
func NewTaskModel(conn sqlx.SqlConn, c cache.CacheConf) TaskModel {
	return &customTaskModel{
		defaultTaskModel: newTaskModel(conn, c),
	}
}

func (m *defaultTaskModel) RowBuilder() squirrel.SelectBuilder {
	return squirrel.Select(taskRows).From(m.table)
}

func (m defaultTaskModel) Truncate(ctx context.Context) {
	build := m.RowBuilder()
	query, values, err := build.ToSql()
	if err == nil {
		var resp []*Task
		err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
		if err == nil {
			for _, r := range resp {
				m.Delete(ctx, r.Id)
			}
			m.ExecNoCacheCtx(ctx, fmt.Sprintf("TRUNCATE %s", m.tableName()))
		}
	}
}

func (m defaultTaskModel) FindAll(ctx context.Context) ([]*Task, error) {
	build := m.RowBuilder()
	query, values, err := build.ToSql()
	if err != nil {
		return nil, nil
	}

	var resp []*Task
	err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
	switch err {
	case nil:
		return resp, nil
	default:
		return nil, err
	}
}

func (m defaultTaskModel) FindAllTaskByGroupId(ctx context.Context, groupId int64) ([]*Task, error) {
	build := m.RowBuilder()
	query, values, err := build.Where(" group_id=? ", groupId).OrderBy("sort_index asc").ToSql()
	if err != nil {
		return nil, nil
	}

	var resp []*Task
	err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
	switch err {
	case nil:
		return resp, nil
	default:
		return nil, err
	}
}
